package fidel.spring.shiro.demo.realm;

import java.security.NoSuchAlgorithmException;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import fidel.spring.shiro.demo.exception.CustomException;
import fidel.spring.shiro.demo.po.ActiveUser;
import fidel.spring.shiro.demo.po.SysPermission;
import fidel.spring.shiro.demo.po.SysUser;
import fidel.spring.shiro.demo.service.SysService;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private SysService sysService;

    public void clearCache() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        // 清除与指定账户身份相关的任何缓存数据
        super.clearCache(principals);
    }

    /**
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
        List<SysPermission> buttons = null;
        // 根据id查询权限
        try {
            sysService.authorize(activeUser);
            buttons = activeUser.getButtons();
        } catch (Exception e) {
            e.printStackTrace();
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 迭代集合，将其中每个元素的指定字符串类型属性添加至授权信息中
        for (SysPermission permission : buttons) {
            authorizationInfo.addStringPermission(permission.getPercode());
        }
        return authorizationInfo;
    }

    /**
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        SysUser sysUser = null;
        ActiveUser activeUser = null;
        try {
            // 验证token的有效性
            sysUser = sysService.authenticate(token);
            activeUser = new ActiveUser(sysUser.getId(), sysUser.getUsercode(), sysUser.getUsername());
            sysService.authorize(activeUser);
        } catch (CustomException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        String salt = sysUser.getSalt();
        // 返回认证信息，由父类AuthenticatingRealm进行认证
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(activeUser,
            sysUser.getPassword(), ByteSource.Util.bytes(salt), getName());
        return simpleAuthenticationInfo;
    }

    /**
     * 如果该认证realm可以处理提交的该类令牌实例，则返回true，否则返回false
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    public String getName() {
        return "customRealm";
    }
}
